package com.flexdms.i18n;

import java.io.IOException;

import javax.faces.component.NamingContainer;
import javax.faces.component.UIComponent;
import javax.faces.component.UINamingContainer;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;



public class LabelRenderer extends BasicRenderer
{

	@Override
	public void encodeBegin(FacesContext context, UIComponent component)
			throws IOException
	{

		if (!component.isRendered())
		{
			return;
		}

		ResponseWriter writer = context.getResponseWriter();

		String forClientId = null;
		String forValue = (String) component.getAttributes().get("for");
		if (forValue != null)
		{
			UIComponent forComponent = getForComponent(context, forValue,
					component);
			if (forComponent == null)
			{
				// it could that the component hasn't been created yet. So
				// construct the clientId for component.
				forClientId = getForComponentClientId(component, context,
						forValue);
			} else
			{
				forClientId = forComponent.getClientId(context);
			}
		}

		
		writer.startElement("label", component);
		writer.writeAttribute("id",  component.getClientId(context),
                "id");
		if (forClientId != null)
		{
			writer.writeAttribute("for", forClientId, "for");
		}

		writeGenericAttributes(component, writer);
		String styleClass = (String) component.getAttributes()
				.get("styleClass");
		if (null != styleClass)
		{
			writer.writeAttribute("class", styleClass, "styleClass");
		}

		// render the curentValue as label text if specified.
		String value = getLocalizedText(component);
		if (value != null && value.length() != 0)
		{
			Object val = component.getAttributes().get("escape");
			boolean escape = (val != null) && Boolean.valueOf(val.toString());

			if (escape)
			{
				writer.writeText(value, component, "value");
			} else
			{
				writer.write(value);
			}
		}
		writer.flush();

	}

	@Override
	public void encodeEnd(FacesContext context, UIComponent component)
			throws IOException
	{

		if (!component.isRendered())
		{
			return;
		}
		ResponseWriter writer = context.getResponseWriter();
		writer.endElement("label");

	}

	
	protected String getForComponentClientId(UIComponent component,
			FacesContext context, String forValue)
	{

		String result = null;
		UIComponent parent = component.getParent();
		while (parent != null)
		{
			if (parent instanceof NamingContainer)
			{
				break;
			}
			parent = parent.getParent();
		}
		if (parent == null)
		{
			return result;
		}
		String parentClientId = parent.getClientId(context);
		result = parentClientId + UINamingContainer.getSeparatorChar(context)
				+ forValue;
		return result;

	}

	

	
}
